package zuk.clipvietfun.clipadapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;

public class LoadImageTask extends AsyncTask<URL, Void, Bitmap>{
	private ImageHolder imgHolder = new ImageHolder();
	public LoadImageTask(ImageHolder imgHolder) {
		this.imgHolder = imgHolder;
	}

	@Override
	protected Bitmap doInBackground(URL... arg0) {
		try {
//            Log.e("src",imgHolder.img_url);
            URL url = new URL(imgHolder.img_url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(input);
//            Log.e("Bitmap","returned");
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("Exception",e.getMessage());
            return null;
        }
	}
	@Override
	protected void onPreExecute() {
		imgHolder.prgBar.setVisibility(View.VISIBLE);
		imgHolder.img_thumb.setVisibility(View.GONE);
		super.onPreExecute();
	}
	@Override
	protected void onCancelled() {
		imgHolder.prgBar.setVisibility(View.VISIBLE);
		imgHolder.img_thumb.setVisibility(View.GONE);
		super.onCancelled();
	}
	@Override
	protected void onPostExecute(Bitmap result) {
		int pos = Integer.parseInt(imgHolder.img_thumb.getTag().toString());
		if(imgHolder.position==pos&&result!=null){
			imgHolder.prgBar.setVisibility(View.GONE);
			imgHolder.img_thumb.setVisibility(View.VISIBLE);
			imgHolder.img_thumb.setImageBitmap(result);
		}
		super.onPostExecute(result);
	}
}
